package com.eolwral.osmonitor;

import android.app.Activity;
import android.app.TabActivity;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TabHost;

public class GestureScroller implements OnGestureListener, OnTouchListener {
	public GestureScroller(Activity activity, View root, int currentTabIndex) {
		this.Activity = activity;
		this.gestureScanner = new android.view.GestureDetector(activity, this);
		if (root != null)
			root.setOnTouchListener(this);
		
		CurrentTab = currentTabIndex;
	}
	
	private TabHost GetTabHost()
	{
		return ((TabActivity) Activity.getParent()).getTabHost();
	}
	
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
	{
		try {
			if (Math.abs(e1.getY() - e2.getY()) > CommonUtil.SWIPE_MAX_OFF_PATH)
				return false;
			else if (e1.getX() - e2.getX() > CommonUtil.SWIPE_MIN_DISTANCE &&
					Math.abs(velocityX) > CommonUtil.SWIPE_THRESHOLD_VELOCITY) 
				GetTabHost().setCurrentTab((CurrentTab + 1) % GetTabHost().getTabWidget().getTabCount());
			else if (e2.getX() - e1.getX() > CommonUtil.SWIPE_MIN_DISTANCE &&
							Math.abs(velocityX) > CommonUtil.SWIPE_THRESHOLD_VELOCITY) {
				if (CurrentTab == 0)
					GetTabHost().setCurrentTab(GetTabHost().getTabWidget().getTabCount() - 1);
				else
					GetTabHost().setCurrentTab((CurrentTab - 1) % GetTabHost().getTabWidget().getTabCount());
			} else
				return false;
		} catch (Exception e) {
			// nothing
		}

		return true;
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		// avoid exception - https://review.source.android.com/#/c/21318/
		try {
			event.getY();
		}
		catch (Exception e) { 
			return false;
		}

		if(gestureScanner.onTouchEvent(event))
		{
			v.onTouchEvent(event);
			return true;
		}
		else
		{
			if(v.onTouchEvent(event))
				return true;
			return false;
		}
	}
	
	public boolean onTouchEvent(MotionEvent me)
	{
		return gestureScanner.onTouchEvent(me);
	}
	
	@Override
	public boolean onDown(MotionEvent e)
	{
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e)
	{
		return;
	}
	
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
	{
		return false;
	}
	
	@Override
	public void onShowPress(MotionEvent e)
	{
		return;
	} 
	
	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}
	
	private Activity Activity;
	private int CurrentTab;
	private android.view.GestureDetector gestureScanner;
}
